<script setup>
import { ref } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { postNavAdd } from '@/apis/apis.js'
import { getFormattedDate } from '@/utils/utils.js'

const props = defineProps(['level'])

const dialogVisible = ref(false)
const form = ref({
  name: '',
  path: '',
  icon: '',
  sort: '0',
  status: '1'
})
const rules = ref({
  name: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入类别名称'
    }
  ],
  path: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入导航路径'
    }
  ],
})
const formRef = ref(null)
const route = useRoute()

const updateVisible = (value) => {
  dialogVisible.value = value
}
const handleAdd = () => {
  formRef.value.validate(async (isValid) => {
    if (isValid) {
      const data = {
        parent_id: route.query.parent_id,
        ...form.value,
        create_time: getFormattedDate(),
        level: String(props.level)
      }
      try {
        const res = await postNavAdd(data)
        if (!res.status) {
          ElMessage({ type: 'info', message: res.msg })
        }
        else {
          ElMessage({ type: 'success', message: res.msg })
          dialogVisible.value = false
          emits('reload')
        }
      }
      catch (err) {
        ElMessage({ type: 'info', message: '网络异常' })
      }
    }
  })
}

defineExpose({
  updateVisible
})

const emits = defineEmits(['reload'])
</script>

<template>
  <el-dialog v-model="dialogVisible" title="添加类别" width="500">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="50" hide-required-asterisk>
      <el-form-item prop="name" label="名称">
        <el-input v-model.trim="form.name" placeholder="请填写名称" />
      </el-form-item>
      <el-form-item prop="path" label="路径">
        <el-input v-model.trim="form.path" placeholder="请填写路径" />
      </el-form-item>
      <el-form-item label="图标">
        <el-input v-model.trim="form.icon" />
      </el-form-item>
      <el-form-item label="排序">
        <el-input v-model.trim="form.sort" disabled />
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="form.status">
          <el-radio value="1">显示</el-radio>
          <el-radio value="0">隐藏</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleAdd">添加</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<style scoped></style>
